package codeTop;

public class q114 {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root);
    }
    TreeNode dfs(TreeNode node){
        if (node == null) {
            return null;
        }
        TreeNode left = dfs(node.left);
        TreeNode right = dfs(node.right);
        if (left == null && right == null) {
            return node;
        }
        if (left == null) {
            return right;
        }
        if (right == null) {
            node.right = node.left;
            node.left = null;
            return left;
        }
        left.right = node.right;
        node.right = node.left;
        node.left = null;
        return right;
    }
}
